package jp.co.systemi.asp.workflow.user;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import jp.co.systemi.asp.utils.LazyLoadingList;
import jp.co.systemi.asp.workflow.Main;
import jp.co.systemi.asp.workflow.annotation.FormInput;
import jp.co.systemi.asp.workflow.data.User;
import jp.co.systemi.asp.workflow.data.UserGroupMeta;
import jp.co.systemi.asp.workflow.group.GroupRef;
import jp.co.systemi.asp.workflow.peer.UserPeer;

import org.apache.wicket.PageParameters;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.behavior.SimpleAttributeModifier;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.image.Image;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.PageableListView;
import org.apache.wicket.markup.html.navigation.paging.PagingNavigator;
import org.apache.wicket.model.PropertyModel;
import org.slim3.datastore.Datastore;
import org.slim3.datastore.GlobalTransaction;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class UserSearch extends Main {
    private static final Logger log = Logger.getLogger(UserSearch.class
            .getName());
    int rowPerPage = 10;
    PagingNavigator wi_navi = null;
    public static class UserSearchModel implements Serializable {
        private static final long serialVersionUID = 6884946649985228519L;
        private String loginId;

        public String getLoginId() {
            return loginId;
        }

        public void setLoginId(String loginId) {
            this.loginId = loginId;
        }
    }

    final private UserSearchModel model = new UserSearchModel();
    LazyLoadingList<User> users = new LazyLoadingList<User>() {
        private static final long serialVersionUID = 7141859951545473818L;

        @Override
        public int size() {
            return UserPeer.getSize(model);
        }

        @Override
        public int getCacheSize() {
            return rowPerPage;
        }

        @Override
        public List<User> getPage(int start, int size) {
            return UserPeer.getPage(model, start, size);
        }
    };

    @FormInput
    // @Required
    public TextField<String> loginId = new TextField<String>("wi_loginId",
            new PropertyModel<String>(model, "loginId"));

    public UserSearch() {
        try {
            rowPerPage = Integer.parseInt(getString("rows.per.page"));
        } catch (Exception e) {
            log.info(e.getLocalizedMessage());
        }
        final WebMarkupContainer tblUsers = new WebMarkupContainer(
                "wi_tblUsers");
        tblUsers.setOutputMarkupId(true);

        final PageableListView<User> listview = new PageableListView<User>(
                "wi_trUser", users, rowPerPage) {
            private static final long serialVersionUID = 8901173915946652261L;

            protected void populateItem(ListItem<User> item) {
                UserService userService = UserServiceFactory.getUserService();
                com.google.appengine.api.users.User usr = userService
                        .getCurrentUser();
                String loginId = usr.getEmail();
                final User user = (User) item.getModelObject();
                String oddEven = (user.getSeq() % 2 == 0) ? "even" : "odd";
                log.info("seq : " + user.getSeq());
                item.add(new SimpleAttributeModifier("class", oddEven));

                PageParameters pars = new PageParameters();
                pars.add("loginId", user.getLoginId());
                BookmarkablePageLink<UserRef> link = new BookmarkablePageLink<UserRef>(
                        "wi_tdUserNameLink", UserRef.class, pars);

                link.add(new Label("wi_tdUserName", UserPeer.getName(user)));
                item.add(link);

                pars = new PageParameters();
                log.info("loginId = " + user.getLoginId());
                pars.add("loginId", user.getLoginId());
                link = new BookmarkablePageLink<UserRef>("wi_tdUserLink",
                        UserRef.class, pars);

                link.add(new Label("wi_tdLoginId", new PropertyModel<String>(
                        user, "loginId")));
                item.add(link);

                pars = new PageParameters();

                pars.add("code", user.getGroupCode());
                BookmarkablePageLink<GroupRef> groupLink = new BookmarkablePageLink<GroupRef>(
                        "wi_tdGroupLink", GroupRef.class, pars);

                groupLink.add(new Label("wi_tdGroupName",
                        new PropertyModel<String>(user, "groupName")));
                item.add(groupLink);

                AjaxLink<Object> wi_delete = new AjaxLink<Object>("wi_tdDelete") {
                    private static final long serialVersionUID = 4414373446594913835L;

                    @Override
                    public void onClick(AjaxRequestTarget target) {
                        GlobalTransaction gtx = Datastore
                                .beginGlobalTransaction();
                        List<Key> keys = new ArrayList<Key>();
                        UserGroupMeta ugm = UserGroupMeta.get();
                        List<Key> userGroupKeys = Datastore.query(ugm).filter(
                                ugm.loginId.equal(user.getLoginId()))
                                .asKeyList();
                        keys.addAll(userGroupKeys);
                        keys.add(user.getId());

                        gtx.delete(keys);
                        gtx.commit();
                        // ユニックキーも削除
                        Datastore.deleteUniqueValue(UserReg.UNIQUE_KEY, user
                                .getLoginId());
                        users.remove(user);

                        target.addComponent(tblUsers);
                    }
                };
                wi_delete.setEnabled(userService.isUserAdmin());
                Image image = new Image("wi_deleteImg");
                if(userService.isUserAdmin()){
                    if(user.getLoginId().equals(loginId)){
                        wi_delete.setEnabled(false);
                        image.add(new SimpleAttributeModifier("src", "/images/disable_delete_icon.jpg"));
                    }
                    else{
                        image.add(new SimpleAttributeModifier("src", "/images/delete_icon.jpg"));
                    }
                }
                else{
                    image.add(new SimpleAttributeModifier("src", "/images/disable_delete_icon.jpg"));
                }
                wi_delete.add(image);

                item.add(wi_delete);
            }
        };

        wi_navi = new PagingNavigator("wi_navi", listview);
        Form<UserSearchModel> form = new MainForm<UserSearchModel>(this,
                "wi_userSearchForm") {
            private static final long serialVersionUID = 1L;
            /**
             * 検索ボタン
             */
            @Override
            protected void onSubmitInner() {
                users.clear();
                listview.setCurrentPage(0);
            }
        };

        tblUsers.add(listview);
        tblUsers.add(wi_navi);
        form.add(tblUsers);
    }
}
